import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 从localStorage初始化用户状态
  const initUser = () => {
    try {
      const userStr = localStorage.getItem('user')
      return userStr ? JSON.parse(userStr) : null
    } catch (e) {
      console.error('解析用户信息失败:', e)
      return null
    }
  }
  
  // 状态
  const user = ref(initUser())
  const token = ref(localStorage.getItem('token') || '')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userId = computed(() => user.value?.id || null)
  const username = computed(() => user.value?.username || '')
  const avatar = computed(() => user.value?.avatar || '')

  // 方法
  // 设置用户信息
  function setUser(userData) {
    user.value = userData
  }

  // 设置token
  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 登录
  function login(userData, newToken) {
    setUser(userData)
    setToken(newToken)
  }

  // 退出登录
  function logout() {
    user.value = null
    token.value = ''
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }

  return {
    user,
    token,
    isLoggedIn,
    userId,
    username,
    avatar,
    setUser,
    setToken,
    login,
    logout
  }
}) 